<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/9/10 19:15
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Caigou_Model extends CI_Model
{
    // 构造函数
    function __construct () {
        parent::__construct();
    }

    // 检查用户是否已申请
    function checkIfExists($userid)
    {
        if (empty($userid)) {
            return null;
        }

        $query = $this->db->where(['userid' => $userid])->get('purchaser_apply');
        return $query->row_array();
    }

    // 申请成员采购员
    function apply($userid, Array $params)
    {
        $data = array_merge($params, ['userid' => $userid]);
        return $this->db->insert('purchaser_apply', $data);
    }

    /**
     * 返回总人数
     * @param int $userType
     * @return mixed
     */
    function getTotal($userType = 0)
    {
        $where = [];
        if ($userType != -1) {
            $where['status'] = $userType;
        }

        $db1 = clone($this->db);
        $db1->where($where);
        $counts = $db1->count_all_results('purchaser_apply');
        return $counts;
    }

    /**
     * 采购商列表
     */
    function getUsers($userType = 0, $offset = 0, $limit = 20)
    {
        $where = [];
        if ($userType != -1) {
            $where['p.status'] = $userType;
        }

        $db1 = clone($this->db);
        $db1->where($where);
        $db1->select("p.id, p.userid, p.name, p.phone, p.email, p.wechat, p.company, p.license_url, p.organization_url, p.created_time, p.status, pro.avatar");
        $db1->from('purchaser_apply as p');
        $db1->join('user as u', 'u.id=p.userid');
        $db1->join('user_profile as pro', 'u.id=pro.userId');
        $db1->limit($limit, $offset);
        $db1->order_by('p.created_time', 'DESC');
        $query = $db1->get();

        return $query->result_array();
    }

    /**
     * 获取一条记录
     * @param $id
     * @return mixed
     */
    public function getPurchaserItem($id)
    {
        $query = $this->db->where('id', $id)->get("purchaser_apply");
        return $query->row_array();
    }

    /**
     * 修改记录
     * @param $id
     * @param $status
     * @return mixed
     */
    public function modifyStatus($id, $status)
    {
        return $this->db->where('id', $id)->update('purchaser_apply', [
            'status' => $status
        ]);
    }
}
